import React, { useRef, useState, FC } from 'react';
import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import { Button, Modal, Form, Input, Popconfirm, Select, message } from 'antd';
import type { ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { ViewColumnsItem, customerListItem, MotifItem } from './data.d';
import { viewColumns } from './data';
import {
  getCustomerList,
  getCandidateList,
  addCandidate,
  delCandidate,
} from './services';

type ViewModalProps = {
  viewInfo?: MotifItem;
};

const { Option } = Select;
const { TextArea } = Input;

const ViewModal: FC<ViewModalProps> = ({ viewInfo }) => {
  const [candidateItemModal, setCandidateItemModal] = useState(false);
  // 候选人列表
  const [customerList, setCustomerList] = useState<customerListItem[]>([]);
  const [name, setName] = useState<string>('');

  const confirmDel = async (serialNo: string) => {
    console.log(serialNo);
    let res = await delCandidate({ serialNo });
    if (res.code !== '000000') return message.success('删除失败！');
    message.success('删除成功！');
    actionRef.current?.reload();
  };

  // 定义操作单元格
  const columnsOptionRender = (text: any, record: ViewColumnsItem) => {
    return [
      <div key={record.serialNo}>
        <Popconfirm
          title="是否删除此条数据?"
          onConfirm={() => confirmDel(record.serialNo)}
          onCancel={() => {
            message.warning(`取消删除`);
          }}
          okText="是"
          cancelText="否"
        >
          <a>删除</a>
        </Popconfirm>
      </div>,
    ];
  };

  // 列渲染样式赋值
  viewColumns.forEach((item) => {
    item.dataIndex === 'action'
      ? (item.render = columnsOptionRender)
      : undefined;
  });

  /**
   * 获取客户列表
   */
  const getCustomers = async (nickname?: string) => {
    let res = nickname
      ? await getCustomerList({
          nickname,
          pageSize: 50,
          current: 1,
        })
      : await getCustomerList({
          pageSize: 50,
          current: 1,
        });
    console.log(res);
    if (res.code !== '000000')
      return message.info('获取候选人列表失败，请稍后再试！');
    setCustomerList(res.data);
  };

  /**
   * 点击添加候选人调用
   */
  const showCandidateModal = async () => {
    getCustomers();
    setCandidateItemModal(true);
  };

  /**
   * 搜索客户调用
   * @param nickname 搜索内容
   */
  const searchCustomerNo = (nickname: string) => {
    console.log(nickname);
    getCustomers(nickname);
  };

  /**
   * 选择人改变时调用
   */
  const candidateChange = (e: string) => {
    console.log(e);
    customerList.forEach((item) => {
      if (item.customerNo == e) {
        setName(item.nickname);
      }
    });
  };
  /**
   * 点击新增、修改提案模态框确定调用
   */
  const handleCandidateOk = async () => {
    await candidateForm.validateFields();
    let response = candidateForm.getFieldsValue();
    response.name = name;
    console.log(response);
    let res = await addCandidate({
      ...response,
      electionNo: viewInfo?.serialNo,
    });
    console.log(res);
    if (res.code !== '000000') return message.info('添加失败');
    message.success('添加成功');
    actionRef.current?.reload();
    candidateForm.resetFields();
    setCandidateItemModal(false);
  };

  /**
   * 关闭新增、修改提案模态框调用
   */
  const handleCandidateCancel = () => {
    setCandidateItemModal(false);
  };
  // 绑定表格
  const actionRef = useRef<ActionType>();
  // 绑定表单
  const [candidateForm] = Form.useForm();
  return (
    <>
      <ProTable<ViewColumnsItem>
        actionRef={actionRef}
        scroll={{ x: 900 }}
        columns={viewColumns}
        rowKey="serialNo"
        search={false}
        bordered
        dateFormatter="string"
        headerTitle="候选人管理"
        params={{ electionNo: viewInfo?.serialNo }}
        toolBarRender={() => [
          <Button
            onClick={showCandidateModal}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新增候选人
          </Button>,
        ]}
        // 分页相关配置
        pagination={{
          // 初始页面数据条数
          pageSize: 50,
        }}
        // 请求的数据
        request={async (params) => {
          console.log(params);
          let res = await getCandidateList(params);
          console.log(res);
          return {
            data: res.data,
          };
        }}
      />
      {/* 新增、修改提案模态框 */}
      <Modal
        title="添加候选人"
        visible={candidateItemModal}
        onOk={handleCandidateOk}
        onCancel={handleCandidateCancel}
      >
        <Form
          name="basic"
          form={candidateForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item
            label="候选人"
            name="electedPersonNo"
            rules={[{ required: true, message: '请选择候选人!' }]}
          >
            <Select
              showSearch
              filterOption={false}
              onSearch={searchCustomerNo}
              style={{ width: '100%' }}
              onChange={candidateChange}
            >
              {customerList.map((item) => {
                return item.nickname ? (
                  <Option key={item.customerNo} value={item.customerNo}>
                    {item.nickname}
                  </Option>
                ) : null;
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="候选人描述"
            name="description"
            rules={[{ required: true, message: '请填写提案描述!' }]}
          >
            <TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default ViewModal;
